import { Toast } from "vant";
import { formatCompanyName } from "./string";
import { getCaHomeData } from "@/api/report";

interface ReportStats {
  user: string;
  joinYear: number;
  joinAttendance: string;
  earlyAttendanceDays: number;
  lateAttendaceDays: number;
  yearMostEarlyAttendaceTime: string;
  specialAttendanceLocation: string;
  specialAttendanceQuantity: number;
  travelCityNumber: number;
  travelRate: number;
  travelCities: string[];
  mostUsedApproval: [string, string, string];
  approvalClose: {
    name: string;
    quantity: number;
  };
  emailClose: {
    name: string;
    num: number;
  }[];
  ichangan: {
    update: number;
    app: number;
    user: number;
    service: number;
    logPerDay: number;
    meetingPerDay: number;
    approvalPerDay: number;
    emailPerDay: number;
  };
  system: {
    approval: number;
    attendance: number;
    meetingQuantity: number;
    meetingHours: number;
    email: number;
  };
}

export const formatReportStats = async (raw: any): Promise<ReportStats> => {
  console.log("获取的数据", raw);
  let caHome = {
    beComments: 0, // 被评论数
    beLikeds: 0, // 被点赞数
    beShares: 0, // 被分享数
    beViewNews: 0, // 资讯被浏览数
    beViewPosts: 0, // 帖子被浏览数
    fans: 0, // 新增粉丝数
    fiveWRate: 0, // 5w 完成率
    fiveWShares: 0, // 5w 分享数
    fiveWTasks: 0, // 收到的5w任务数
    likeds: 0, // 点赞数(点赞文章数)
    postedNews: 0, // 发布资讯数
    postedPosts: 0, // 发布帖子数
  };
  const loginId = raw?.data?.userInfo?.loginId || "";
  if (!loginId) {
    Toast.fail("获取员工号失败，请重新登录");
  } else {
    const caHomeData = await getCaHomeData(loginId);
    console.log("长安之家数据", caHomeData);
    if (caHomeData.errorCode !== 200) {
      Toast.fail("长安之家数据获取失败");
    } else {
      caHome = caHomeData.result;
      caHome.fiveWRate = Math.round(caHome.fiveWRate / 100);
    }
  }
  // const joinYear = filterValidOption("USER_SURVIVAL", raw)[0].catagrayChildName;
  const joinYear = filterValidOptionChildCata("USER_SURVIVAL", raw);
  const joinAttendance = formatDateTime("USER_CREATE_TIME", raw);
  const system = {
    approval: filterValidOptionNum("PROC_JOIN_ALL", raw),
    attendance: filterValidOptionNum("USER_CLOCK_MOBILE", raw),
    meetingQuantity: filterValidOptionNum("MEETING_ALL", raw),
    meetingHours: filterValidOptionNum("MEETING_TIME_ALL", raw),
    email: filterValidOptionNum("MAIL_ALL_ALL", raw),
  };
  const approvalClose = {
    name: formatCompanyName(
      // filterValidOption("PROC_PERSON_PARTNER", raw)[0].catagrayChildName
      filterValidOptionChildCata("PROC_PERSON_PARTNER", raw)
    ),
    quantity: filterValidOptionNum("PROC_PERSON_PARTNER", raw),
  };
  const stats = {
    keyword: raw?.data?.keyWord?.keyWord,
    user: formatCompanyName(raw?.data?.userInfo?.userName || ""),
    sex:
      raw.data.userInfo && raw.data.userInfo.sex
        ? formatCompanyName(raw.data.userInfo.sex)
        : "男",
    joinYear,
    ichangan: {
      update: 13,
      app: 104,
      user: 79547,
      service: 184548217,
      logPerDay: 193000,
      meetingPerDay: 414,
      approvalPerDay: 5395,
      emailPerDay: 275902,
    },
    joinAttendance,
    system,
    earlyAttendanceDays: filterValidOptionNum("USER_CLOCK_MORNING", raw),
    lateAttendaceDays: filterValidOptionNum("USER_CLOCK_NIGHT", raw),
    yearMostEarlyAttendaceTime: formatDateTime("USER_CLOCK_FIRST", raw),
    specialAttendanceLocation: filterValidOption("USER_CLOCK_PLACE", raw)[0]
      ?.catagrayChildName,
    specialAttendanceQuantity: filterValidOptionNum("USER_CLOCK_PLACE", raw),
    approvalClose,
    emailClose: formatEmailTop5(raw),
    // 考勤平台数据
    hr: {
      mobileDays: filterValidOptionNum("HR_CLOCK_MOBILE_DAYS", raw),
      mostPlace: filterValidOptionChildCata("HR_CLOCK_MOST_PLACE", raw),
      mostPlaceNum: filterValidOptionNum("HR_CLOCK_MOST_PLACE", raw),
      lateNight: filterValidOptionNum("HR_CLOCK_LATE_NIGHT", raw),
    },
    //  差旅
    travelNumber: filterValidOptionNum("TRIP_ALL", raw), // 出差次数
    travelCityNumber: formatTravelCitiesTop(raw, 3).travelCityNumber,
    travelRate: calculateTravelRate(raw),
    travelCities: formatTravelCitiesTop(raw, 3).travelCities,
    mostUsedApproval: formatApprovalTop3("PROC_JOIN_DEF_ALL", raw),

    // 学习平台数据
    ilearning: {
      learningLecturerAll: filterValidOptionNum("LEARNING_LECTURER_ALL", raw),
      learningLecturerPersonAll: filterValidOptionNum(
        "LEARNING_LECTURER_PERSON_ALL",
        raw
      ),
      learningLecturerPopularName: formatPopularLesson(
        "LEARNING_LECTURER_POPULAR",
        raw
      ).learningLecturerPopularName,
      learningLecturerPopularMark: formatPopularLesson(
        "LEARNING_LECTURER_POPULAR",
        raw
      ).learningLecturerPopularMark,
      learningTaskComplete: filterValidOptionNum("LEARNING_TASK_COMPLETE", raw),
      learningStudyCourse: filterValidOptionNum("LEARNING_STUDY_COURSES", raw),
      learningClassHours: filterValidOptionNum("LEARNING_CLASS_HOURS", raw),
      learningMostInterestingCategory: filterValidOptionChildCata(
        "LEARNING_MOST_INTERESTING_CATEGORY",
        raw
      ),
      learningRecommendedCourses:
        filterValidOptionChildCata("LEARNING_RECOMMENDED_COURSES", raw) ||
        "云计算基础培训,揭秘新能源 拥抱电动化,“数字化+”思维助力 愉悦驾乘素质基因打造",
    },
    caHome,
    // 荣誉数据
    honorData: {
      hrStandGrade: filterValidOptionChildCata("HR_STAND_GRADE", raw), // 变更后的职级
      hrPosition: filterValidOptionChildCata("HR_POSITION", raw), // 变更后的职务
      hrProfessionalCompetence: filterValidOptionChildCata(
        "HR_PROFESSIONAL_COMPETENCE",
        raw
      ), // 变更后的专业能力
      honor6sigmaProject: filterValidOptionChildCata(
        "HONOR_6SIGMA_PROJECT",
        raw
      ), // 6Sigma认证项目名称
      intent: filterHonorPatent("HONOR_PATENT_APPLICATION", raw).intent, // 专利申请数量-发明
      utility: filterHonorPatent("HONOR_PATENT_APPLICATION", raw).utility, // 专利申请数量-实用新型
      design: filterHonorPatent("HONOR_PATENT_APPLICATION", raw).design, // 专利申请数量-外观设计
      honorSoftwareCopyright: filterValidOptionNum(
        "HONOR_SOFTWARE_COPYRIGHT",
        raw
      ), // 软件著作权
    },
  };

  return Promise.resolve(stats);
};

const filterValidOption = (key: string, raw: any) =>
  raw.data.reportData.filter((i) => i.catagrayName === key);

const filterValidOptionNum = (key: string, raw: any) =>
  raw.data.reportData.filter((i) => i.catagrayName === key)[0]?.opNum
    ? raw.data.reportData.filter((i) => i.catagrayName === key)[0]?.opNum
    : 0;

const filterValidOptionRank = (key: string, raw: any) =>
  raw.data.reportData.filter((i) => i.catagrayName === key)[0].SEQ_NUM;

// 邮件联系人top5
const formatEmailTop5 = (raw: any) => {
  const list = filterValidOption("MAIL_PERSON_ALL", raw);

  const top5List = list.slice(0, 5);

  return top5List.map((i) => ({
    name: formatCompanyName(i.catagrayChildName),
    num: i?.opNum,
  }));
};

const formatDateTime = (key: string, raw: any) => {
  const rawTime = filterValidOption(key, raw)[0]?.catagrayChildName;

  if (!rawTime) return "无";

  const timeArr = rawTime.replace("/", "年").replace("/", "月").split(" ");
  const date = timeArr[0] + "日";
  return date + " " + timeArr[1];
};

// const formatjoinDateTime = (key: string, raw: any) => {
//   const rawTime = filterValidOption(key, raw)[0]?.catagrayChildName;

//   if (!rawTime) return "无";

//   const timeArr = rawTime.replace("-", "年").replace("-", "月").split(" ");
//   const date = timeArr[0] + "日";
//   const time = date + " " + timeArr[1];
//   const lastArr = time.split(":");
//   return lastArr[0] + ":" + lastArr[1];
// };

const calculateTravelRate = (raw: any) =>
  // 48986 公司总人数
  Math.floor((1 - filterValidOptionRank("TRIP_ALL", raw) / 48986) * 100);

const formatApprovalTop3 = (key: string, raw: any) => {
  const list = filterValidOption(key, raw);

  const top3List = list.slice(0, 3);

  return top3List.map((i) => i.catagrayChildName);
};

// 获取出差地址
const formatTravelCitiesTop = (raw: any, num: number) => {
  const citiesArr = filterValidOption("TRIP_DEST", raw);

  if (citiesArr.length === 0) return citiesArr;

  // 排名
  citiesArr.sort((a, b) => b.opNum - a.opNum);

  console.log("citiesArr", citiesArr);

  // 取前五
  const travelCities = citiesArr.slice(0, num).map((i) => {
    console.log("----i----", i);
    return i?.catagrayChildName;
  });
  return {
    travelCityNumber: citiesArr.length,
    travelCities,
  };
};
// 最受欢迎的课程
const formatPopularLesson = (key: string, raw: any) => {
  const learningLecturerPopularName =
    raw.data.reportData.filter((i) => i.catagrayName === key)[0]
      ?.catagrayChildName || "";
  const learningLecturerPopularMark =
    raw.data.reportData.filter((i) => i.catagrayName === key)[0]?.opNum || 0;
  return {
    learningLecturerPopularName,
    learningLecturerPopularMark,
  };
};
const filterValidOptionChildCata = (key: string, raw: any) =>
  raw.data.reportData.filter((i) => i.catagrayName === key)[0]
    ?.catagrayChildName
    ? raw.data.reportData.filter((i) => i.catagrayName === key)[0]
        ?.catagrayChildName
    : "";
const filterHonorPatent = (key: string, raw: any) => {
  return {
    intent:
      raw.data.reportData.filter(
        (i) => i.catagrayName === key && i.catagrayChildName === "INVENT"
      )[0]?.opNum || 0,
    utility:
      raw.data.reportData.filter(
        (i) => i.catagrayName === key && i.catagrayChildName === "UTILITY_MODEL"
      )[0]?.opNum || 0,
    design:
      raw.data.reportData.filter(
        (i) =>
          i.catagrayName === key && i.catagrayChildName === "INDUSTRIAL_DESIGN"
      )[0]?.opNum || 0,
  };
};
